package cn.bluemobi.app.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;

import cn.bluemobi.app.core.utils.PropertiesUtils;
import cn.bluemobi.app.utils.io.rong.RongCloud;
import cn.bluemobi.app.utils.io.rong.models.TokenResult;

/**
 * @Description 融云请求帮助类
 * @date 2017-05-05
 * @author lvjj
 */
public class RongCloudUtils {

    /** 测试 */
    private static final String appKey = PropertiesUtils.getProperty("RONG_APPKEY");

    private static final String appSecret = PropertiesUtils.getProperty("RONG_APPSECRET");

    private static final String APPKEY = "RC-App-Key";

    private static final String NONCE = "RC-Nonce";

    private static final String TIMESTAMP = "RC-Timestamp";

    private static final String SIGNATURE = "RC-Signature";

    private static final String UTF8 = "UTF-8";

    /** 获取token */
    public final static String RONGHUB_GETTOKEN = "https://api.cn.ronghub.com/user/getToken.json";

    public static void main(String[] args) throws Exception {

        // String rongStr =
        // "{\"code\":\"200\",\"result\":{\"code\":200,\"userId\":\"1\",\"token\":\"aMRh78oqnCU3oEwvy5vmy7p4DLlVqhbHOf+2cg2xunzvqtC6mvMMN/I8v21U9r90E6cx4hDnWinzlBJ0Lh7PSA==\"}}";
        // try {
        // // 获取融云token
        // List<Map<String, Object>> rongList = new ArrayList<Map<String,
        // Object>>();
        // Map<String, Object> rongMap1 = new HashMap<String, Object>();
        // rongMap1.put("Rkey", "userId");
        // rongMap1.put("Rvalue", "1");
        // Map<String, Object> rongMap2 = new HashMap<String, Object>();
        // rongMap2.put("Rkey", "name");
        // rongMap2.put("Rvalue", "");
        // Map<String, Object> rongMap3 = new HashMap<String, Object>();
        // rongMap3.put("Rkey", "portraitUri");
        // rongMap3.put("Rvalue", "");
        // rongList.add(rongMap1);
        // rongList.add(rongMap2);
        // rongList.add(rongMap3);
        // SdkHttpResult sdkHttpResult =
        // RongCloudUtils.roogPostPublic(RongCloudUtils.RONGHUB_GETTOKEN,
        // rongList);
        // System.out.println(sdkHttpResult.toString());
        // } catch (Exception e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);

        System.out.println("************************User********************");
        // 获取 Token 方法
        TokenResult userGetTokenResult = rongCloud.user.getToken("10", "", "");
        System.out.println("getToken:  " + userGetTokenResult.toString());
        System.out.println(userGetTokenResult.getToken());
    }

    /** 融云公共方法 */
    public static SdkHttpResult roogPostPublic(String urlStr, List<Map<String, Object>> list) throws Exception {
        // 添加签名header
        String nonce = String.valueOf(Math.random() * 1000000);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        StringBuilder toSign = new StringBuilder(appSecret).append(nonce).append(timestamp);
        String sign = hexSHA1(toSign.toString());

        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setInstanceFollowRedirects(true);
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);

        conn.setRequestProperty(APPKEY, appKey);
        conn.setRequestProperty(NONCE, nonce);
        conn.setRequestProperty(TIMESTAMP, timestamp);
        conn.setRequestProperty(SIGNATURE, sign);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                sb.append(list.get(i).get("Rkey") + "=").append(
                        URLEncoder.encode(list.get(i).get("Rvalue").toString(), UTF8));
            } else {
                sb.append("&" + list.get(i).get("Rkey") + "=").append(
                        URLEncoder.encode(list.get(i).get("Rvalue").toString(), UTF8));
            }

        }
        setBodyParameter(sb, conn);
        return returnResult(conn);
    }

    public static String hexSHA1(String value) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(value.getBytes("utf-8"));
            byte[] digest = md.digest();
            return byteToHexString(digest);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static String byteToHexString(byte[] bytes) {
        return String.valueOf(Hex.encodeHex(bytes));
    }

    // 设置body体
    public static void setBodyParameter(StringBuilder sb, HttpURLConnection conn) throws IOException {
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(sb.toString());
        out.flush();
        out.close();
    }

    // 添加签名header
    public static HttpURLConnection CreatePostHttpConnection(String uri) throws MalformedURLException, IOException,
            ProtocolException {
        String nonce = String.valueOf(Math.random() * 1000000);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        StringBuilder toSign = new StringBuilder(appSecret).append(nonce).append(timestamp);
        String sign = hexSHA1(toSign.toString());

        URL url = new URL(uri);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setInstanceFollowRedirects(true);
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);

        conn.setRequestProperty(APPKEY, appKey);
        conn.setRequestProperty(NONCE, nonce);
        conn.setRequestProperty(TIMESTAMP, timestamp);
        conn.setRequestProperty(SIGNATURE, sign);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        return conn;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }

    public static SdkHttpResult returnResult(HttpURLConnection conn) throws Exception, IOException {
        String result;
        InputStream input = null;
        if (conn.getResponseCode() == 200) {
            input = conn.getInputStream();
        } else {
            input = conn.getErrorStream();
        }
        result = new String(readInputStream(input));
        return new SdkHttpResult(conn.getResponseCode(), result);
    }
}
